package handler

import (
	"ecom-manager/cache"
	"ecom-manager/model"
	"ecom-manager/pck"
	"encoding/json"
	"github.com/gin-gonic/gin"
	"strconv"
	"time"
)

func Login(c *gin.Context) {
	username := c.PostForm("username")
	password := c.PostForm("password")
	if username == "" || password == "" {
		c.JSON(200, gin.H{"code": 500, "msg": "账号和密码不能为空"})
		return
	}
	var user model.User
	redis_key := "login_error_" + username
	errCout, _ := cache.Rdb.Get(cache.Ctx, redis_key).Int()
	if errCout >= 3 {
		c.JSON(200, gin.H{"code": 500, "msg": "密码错误3次，禁止登录"})
		return
	}
	err := model.DB.Where("username=?", username).Find(&user).Error
	if err != nil {
		c.JSON(200, gin.H{"code": 500, "msg": "查询失败"})
		return
	}
	if user.ID == 0 {
		c.JSON(200, gin.H{"code": 500, "msg": "账号或密码错误"})
		return
	}
	if user.Password != pck.Md5(password) {
		cache.Rdb.Incr(cache.Ctx, redis_key)
		if errCout == 2 {
			cache.Rdb.Set(cache.Ctx, redis_key, 3, time.Hour*2)
			c.JSON(200, gin.H{"code": 500, "msg": "密码错误3次，禁止2个小时登录"})
			return
		} else {
			c.JSON(200, gin.H{"code": 500, "msg": "账号或密码错误"})
			return
		}
	}
	c.JSON(200, gin.H{"code": 200, "msg": "登录成功", "data": user})
}
func AddUserRole(c *gin.Context) {
	uid, _ := strconv.Atoi(c.PostForm("uid"))
	rid, _ := strconv.Atoi(c.PostForm("rid"))
	userRole := model.UserRole{
		Uid: uid,
		Rid: rid,
	}
	err := model.DB.Create(&userRole).Error
	if err != nil {
		c.JSON(200, gin.H{"code": 500, "msg": "添加失败"})
		return
	}
	c.JSON(200, gin.H{"code": 200, "msg": "添加成功"})
}
func UserRoleList(c *gin.Context) {
	uid := c.Query("uid")
	var role []model.Role
	err := model.DB.Table("roles").
		Joins("left join user_roles on roles.id=user_roles.rid").
		Where("user_roles.uid=?", uid).
		Find(&role).Error
	if err != nil {
		c.JSON(200, gin.H{"code": 500, "msg": "查询失败"})
	}
	c.JSON(200, gin.H{"code": 200, "msg": "查询成功", "data": role})
}
func RoleNodeList(c *gin.Context) {
	rid := c.Query("rid")
	var node []model.Node
	err := model.DB.Table("nodes").
		Joins("left join role_nodes on nodes.id=role_nodes.nid").
		Where("role_nodes.rid=?", rid).
		Find(&node).Error
	if err != nil {
		c.JSON(200, gin.H{"code": 500, "msg": "查询失败"})
	}
	c.JSON(200, gin.H{"code": 200, "msg": "查询成功", "data": node})
}
func AddGood(c *gin.Context) {
	good_code := c.PostForm("good_code")
	good_name := c.PostForm("good_name")
	good_price, _ := strconv.Atoi(c.PostForm("good_code"))
	good := model.Good{
		GoodCode:  good_code,
		GoodName:  good_name,
		GoodPrice: good_price,
	}
	err := model.DB.Create(&good).Error
	if err != nil {
		c.JSON(200, gin.H{"code": 500, "msg": "添加失败"})
		return
	}
	c.JSON(200, gin.H{"code": 200, "msg": "添加成功"})
}
func AddGoodOrder(c *gin.Context) {
	order_code := c.PostForm("order_code")
	order_name := c.PostForm("order_name")
	order_price, _ := strconv.Atoi(c.PostForm("order_price"))
	good_id, _ := strconv.Atoi(c.PostForm("good_id"))
	order := model.GoodOrder{
		OrderCode:  order_code,
		OrderName:  order_name,
		OrderPrice: order_price,
		GoodId:     good_id,
	}
	err := model.DB.Create(&order).Error
	if err != nil {
		c.JSON(200, gin.H{"code": 500, "msg": "添加失败"})
		return
	}
	c.JSON(200, gin.H{"code": 200, "msg": "添加成功"})
}
func GoodOrderList(c *gin.Context) {
	var data []model.GoodOrderList
	redis_key := "list"
	cacheData, _ := cache.Rdb.Get(cache.Ctx, redis_key).Result()
	if cacheData == "" {
		model.DB.Table("good_orders").Select("order_code as OrderCode",
			"order_name as OrderName",
			"order_price as OrderPrice",
			"good_code as GoodCode",
			"good_name as GoodName",
			"good_price as GoodPrice").
			Joins("LEFT JOIN goods ON good_orders.good_id = goods.id").
			Debug().
			Find(&data)
		jsonData, _ := json.Marshal(data)
		cache.Rdb.Set(cache.Ctx, redis_key, jsonData, time.Hour*2)
	} else {
		json.Unmarshal([]byte(cacheData), &data)
	}
	var total int64
	model.DB.Model(&model.GoodOrder{}).Count(&total)
	c.JSON(200, gin.H{"code": 200, "msg": "查询成功", "data": data, "total": total})
}
func DetailGoodOrderList(c *gin.Context) {
	id := c.Query("id")
	var data model.GoodOrderList
	redis_key := "data_id_" + id
	cacheData, _ := cache.Rdb.Get(cache.Ctx, redis_key).Result()
	if cacheData == "" {
		model.DB.Table("good_orders").Select("order_code as OrderCode",
			"order_name as OrderName",
			"order_price as OrderPrice",
			"good_code as GoodCode",
			"good_name as GoodName",
			"good_price as GoodPrice").
			Joins("LEFT JOIN goods ON good_orders.good_id = goods.id").
			Debug().Where("good_orders.id=?", id).
			Find(&data)
		jsonData, _ := json.Marshal(data)
		cache.Rdb.Set(cache.Ctx, redis_key, jsonData, time.Hour*2)
	} else {
		json.Unmarshal([]byte(cacheData), &data)
	}
	c.JSON(200, gin.H{"code": 200, "msg": "查询成功", "data": data})
}
